﻿#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include<mutex>
#include<fstream>
#include<ctime>
#include <cstdlib>
#include <memory>
using namespace std;


#define LOGAPP logger::getInstance()

//单例类
class logger
{
public:

	//两个线程加锁
	static logger* getInstance()
	{
		if (m_log == nullptr) {
			lock_guard<mutex> lock(m_mutex);
			if (m_log == nullptr) {
				m_log = new logger();
			}
		}
		return m_log;
	}

	void writeLog(const string& LogInfo);

	
private:
	logger() {};
	virtual ~logger() {};
	friend class auto_ptr<logger>;
	static logger* m_log;;//本身的类名指针变量实例，私有线程安全
	static mutex m_mutex;//静态锁
	char tmp[100];
	ofstream ofs;//输出文件流
	class CGarbo // 它的唯一工作就是在析构函数中删除logger的实例
	{
	public:
		~CGarbo()
		{
			if (logger::m_log)
			{
				logger::m_log->ofs.close();//关闭文件流
				delete logger::m_log;
				logger::m_log = nullptr;
			}
		}
	};
	static CGarbo Garbo;
};

logger* logger::m_log = nullptr;
mutex logger::m_mutex;



void logger::writeLog(const string& LogInfo)
{
	time_t t = time(0);
	strftime(tmp, sizeof(tmp), "[%Y.%m.%d %X %A]", localtime(&t));
	ofs << LogInfo.c_str() <<tmp<<endl;
}

//测试日志写入
#define NUM 1000//单次写入的日志条数

char logdata[NUM][100];

double random(double start, double end)
{
	return start + (end - start) * rand() / (RAND_MAX + 1.0);
}


int main()
{
	//LOGAPP->writeLog("hello");
	clock_t t1, t2;
	int sum_time = 0;
	//测试10次
	for (int k = 0; k < 10; k++)
	{
		//生成随机数据
		t1 = clock();
		for (int i = 0; i < NUM; i++)
		{
			for (int j = 0; j < 100 - 1; j++)
			{
				logdata[i][j] = rand() % 74 + 48;
			}
			logdata[i][99] = '\0';
		}
		t2 = clock();
		cout << "生成日志数据" << NUM << "条,耗费时间:" << (t2 - t1) << "ms" << endl;

		// 进行日志写入
		t1 = clock();
		for (int i = 0; i < NUM; ++i)
			LOGAPP->writeLog(logdata[i]);
		t2 = clock();
		cout << "写入日志数据" << NUM << "条,耗费时间:" << (t2 - t1) << "ms" << endl;
		sum_time += t2 - t1;
		
	}
	cout << "平均每次花费时间为:" << sum_time / 10 << "ms" << endl;
	system("pause");

	return 0;
}